package neptune.manager.allocator;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;

/**
 * La coda dei task
 * 
 * @author Luigi Lorenzo Arpino
 * 
 */
public class JobQueue {

	private Queue<Job> jobQueue;

	private static JobQueue instance = new JobQueue();

	public static JobQueue getInstance() {
		return instance;
	}

	private JobQueue() {
		this.jobQueue = new LinkedList<Job>();
	}

	public synchronized void enqueue(Job job) {
		this.jobQueue.add(job);
	}

	public synchronized Job getJob(String taskId, String jobId) {
		Iterator<Job> it = this.jobQueue.iterator();
		for (int i = 0; it.hasNext(); i++) {
			Job job = (Job) it.next();
			if (job.getTaskId().equalsIgnoreCase(taskId)
					&& job.getId().equalsIgnoreCase(jobId)) {
				return job;
			}
		}
		return null;
	}

	public synchronized String[][] getAllJob() {
		String[][] result = new String[this.jobQueue.size()][3];
		Iterator<Job> it = this.jobQueue.iterator();
		for (int i = 0; it.hasNext(); i++) {
			Job job = (Job) it.next();
			result[i][0] = job.getDescription();
			result[i][1] = job.getStateDescription();
			result[i][2] = job.getElapsedTime();
		}
		return result;
	}

	public synchronized void removeAllFinishedJobs() {
		Queue<Job> oldQueue = this.jobQueue;
		this.jobQueue = new LinkedList<Job>();
		for (int i = 0; i < oldQueue.size(); i++) {
			Job job = oldQueue.poll();
			if (job.getSate() != Job.STATE_FINISH) {
				this.jobQueue.add(job);
			}
		}
	}

}
